package hello.app;

import hello.app.model.HelloSetting;
import hello.app.model.ModelManager;
import hello.app.util.Debug;
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public class PhoneStateObserver extends PhoneStateListener {

	public boolean mEnabled = false;
	private static PhoneStateObserver instacnce;
	private TelephonyManager mTelephonyManager;
	private PhoneHandler mHandler;
	private HelloSetting mSetting;

	private PhoneStateObserver(Context context){
		mSetting = ModelManager.getInstatce(context).getHelloSetting();
		mHandler = new PhoneHandler(context);
		mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		mTelephonyManager.listen(this, PhoneStateListener.LISTEN_CALL_STATE);
	}

	public static PhoneStateObserver getInstance(Context context){
		if(instacnce == null){
			instacnce = new PhoneStateObserver(context);
		}
		return instacnce;
	}

	public void start(){
		mEnabled = true;
	}

	public void stop(){
		mEnabled = false;
	}

	@Override
	public void onCallStateChanged(int state, String number) {
		super.onCallStateChanged(state, number);
		if(!mEnabled && !mSetting.isServiceEnabled())
			return;

		try {
		switch (state) {
			case TelephonyManager.CALL_STATE_RINGING:
				mHandler.onRinging(number);
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				mHandler.onOffHook(number);
				break;
			case TelephonyManager.CALL_STATE_IDLE:
				mHandler.onIdle();
				break;
			}
		} catch (Exception e) {
			String error = e.getMessage();
			if(error != null){
				Debug.error(error);
			}
			//Log.d(Debug.TAG, e.getMessage());
		}
	}
}
